package com.yuexunit.mobilenurse.module.PatientDetail.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.AppContext;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodCollection.model.impl.BloodCollectionModel;
import com.yuexunit.mobilenurse.module.BloodCollection.presenter.IBloodCollectionPresenter;
import com.yuexunit.mobilenurse.module.BloodCollection.presenter.impl.BloodCollectionPresenter;
import com.yuexunit.mobilenurse.module.BloodCollection.ui.view.IBloodCollectionView;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.Act_DocAdvice;
import com.yuexunit.mobilenurse.module.HealthArticles.ui.Act_Article;
import com.yuexunit.mobilenurse.module.HospitalInfo.Act_HospitalInfo;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.Collectinfo;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.Patient_Patinfo;
import com.yuexunit.mobilenurse.module.PatientDetail.model.impl.PatientDetailModel;
import com.yuexunit.mobilenurse.module.PatientDetail.presenter.IPatientDetailPresenter;
import com.yuexunit.mobilenurse.module.PatientDetail.presenter.impl.PatientDetailPresenter;
import com.yuexunit.mobilenurse.module.PatientDetail.ui.view.IPatientDetailView;
import com.yuexunit.mobilenurse.module.Satisfaction.ui.Act_Satisfaction;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sign_Single;
import com.yuexunit.mobilenurse.module.SignInput.ui.Act_Signs_Input;
import com.yuexunit.mobilenurse.module.SkinTest.ui.Act_SkinTestDetail;
import com.yuexunit.mobilenurse.module.Transportation.ui.Act_Transportation;
import com.yuexunit.mobilenurse.module.TxtNode.ui.Act_TxtWirte;
import com.yuexunit.mobilenurse.module.NursingDocuments.ui.Act_Document;
import com.yuexunit.mobilenurse.util.DateUtil;
import com.yuexunit.mobilenurse.widget.Dialog_BloodPass;
import com.yuexunit.mobilenurse.widget.Dialog_BloodRepeat;
import com.yuexunit.mobilenurse.widget.Dialog_BloodUnpass;
import com.yuexunit.mobilenurse.widget.Dialog_Fail;
import com.yuexunit.mobilenurse.widget.Dialog_Success;
import com.yuexunit.mobilenurse.widget.FixedSwipeListView;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/6/8.
 */
public class Act_PatientDetail_Lachsis extends KJActivity implements IPatientDetailView ,IBloodCollectionView {
    //病人基本信息组件
    @Bind(R.id.patient_pic)
    public ImageView patient_pic;
    @Bind(R.id.patient_name)
    public TextView patient_name;
    @Bind(R.id.patient_grade)
    public TextView patient_grade;
    @Bind(R.id.patient_age)
    public TextView patient_age;
    @Bind(R.id.patient_sex)
    public TextView patient_sex;
    @Bind(R.id.patient_doc)
    public TextView patient_doc;
    @Bind(R.id.patient_bed)
    public TextView patient_bed;
    @Bind(R.id.patient_date)
    public TextView patient_date;
    @Bind(R.id.patient_hospital)
    public TextView patient_hospital;
    @Bind(R.id.patient_lesion)
    public TextView patient_lesion;
    @Bind(R.id.patient_diagnose)
    public TextView patient_diagnose;
    @Bind(R.id.patient_paniclist)
    FixedSwipeListView patientPaniclist;
    @Bind(R.id.patient_state_tv)
    public TextView patient_state_tv;
    @Bind(R.id.patient_state)
    public TextView patient_state;
    //当前病人住院号
    private String Visitno;
    //日期显示格式
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
    private IPatientDetailPresenter presenter;
    private LoadingDialog dialog;

    //扫描号码
    String code;

    //采血成功计时
    Handler handler_blood;
    Timer time;
    TimerTask timetask;
    int countTime = 3;

    Dialog_Success.Builder builder_success;
    IBloodCollectionPresenter presenter_bloodcollection;

    private ValueBroadcastReceiver valueBroadcastReceiver = null;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_patientdetail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        dialog = new LoadingDialog(aty);
        presenter = new PatientDetailPresenter(new PatientDetailModel(), this);
        presenter_bloodcollection = new BloodCollectionPresenter(new BloodCollectionModel(),this);
        Visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
    }

    @Override
    public void initWidget() {
        super.initWidget();
        presenter.showPatientDetail(Visitno);
    }

    @OnClick({R.id.find_plugin_1, R.id.find_plugin_2, R.id.find_plugin_3, R.id.find_plugin_4, R.id.find_plugin_5,
            R.id.find_plugin_6, R.id.find_plugin_7, R.id.find_plugin_8, R.id.find_plugin_9,R.id.titlebar_img_back
            , R.id.find_plugin_10})
    public void PatientFunction(View view) {
        switch (view.getId()) {
            case R.id.find_plugin_1:  //医嘱
                Bundle bundle = new Bundle();
                bundle.putString("source", AppConfig.CLICK);
                showActivity(aty, Act_DocAdvice.class, bundle);
                break;
            case R.id.find_plugin_2: //体征
                showActivity(aty, Act_Signs_Input.class);
                break;
            case R.id.find_plugin_3: //皮试
                showActivity(aty, Act_SkinTestDetail.class);
                break;
            case R.id.find_plugin_4: //护理计费
                ViewInject.toast("正在研发");
                break;
            case R.id.find_plugin_5://住院档案
                showActivity(aty, Act_HospitalInfo.class);
                break;
            case R.id.find_plugin_6://满意度调查
                showActivity(aty, Act_Satisfaction.class);
                break;
            case R.id.find_plugin_7://护理笔记
                showActivity(aty, Act_TxtWirte.class);
                break;
            case R.id.find_plugin_8://健康宣教
                showActivity(aty, Act_Article.class);
                break;
            case R.id.find_plugin_9://手术转运
                showActivity(aty, Act_Transportation.class);
                break;
            case R.id.find_plugin_10://护理文书
                showActivity(aty, Act_Document.class);
                break;
            case R.id.titlebar_img_back:
                finish();
                break;
        }
    }

    @Override
    public void showPatientDetail(Patient_Patinfo currentPatient) {
        //判断当前向服务器发送的病人住院号请求与服务器发回来的病人是否一致
        if (Visitno != null) {
            if (!Visitno.equals(currentPatient.getVisit_no())) {
                ViewInject.toast("服务器返回数据错误");
                return;
            }
        }

        //其中保存当前病人的床号到当前病人信息中
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE, currentPatient.getBedcode());
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME, currentPatient.getName());
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_PRE, currentPatient.getPrepay() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_TOTAL, currentPatient.getTotalfee() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_DATE, currentPatient.getAdmissiondate() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_AGE, currentPatient.getAge()+ "");

        if ("1".equals(currentPatient.getSex()) && currentPatient.getAge() > AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_male_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "男");
        } else if ("1".equals(currentPatient.getSex()) && currentPatient.getAge() < AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_boy_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "男");
        } else if ("2".equals(currentPatient.getSex()) && currentPatient.getAge() > AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_female_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "女");
        } else {
            patient_pic.setImageResource(R.drawable.pic_girl_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "女");
        }

        patient_name.setText(currentPatient.getName());
        patient_grade.setText(currentPatient.getGradename() + "级");
        patient_age.setText(currentPatient.getAge() + "");
        if ("1".equals(currentPatient.getSex())) {
            patient_sex.setText("男");
        } else if ("2".equals(currentPatient.getSex())) {
            patient_sex.setText("女");
        } else {
            patient_sex.setText("不详");
        }
        patient_doc.setText(currentPatient.getMdoctorname());
        patient_bed.setText(currentPatient.getBedcode());
        patient_hospital.setText(currentPatient.getVisit_no());
        patient_lesion.setText(currentPatient.getWardname());
        patient_diagnose.setText(currentPatient.getDiagnosis());
        patient_date.setText(currentPatient.getAdmissiondate());

        if(null != currentPatient.getOps_time())
        {
            patient_state_tv.setText("术后：");
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                patient_state.setText(DateUtil.getDaySub(dateFormat.format(format.parse(currentPatient.getOps_time())), dateFormat.format(now))+"天");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        else {
            patient_state_tv.setText("入院：");
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            patient_state.setText(DateUtil.getDaySub(currentPatient.getAdmissiondate(),dateFormat.format(now))+"天");
        }
    }


    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                dialog.dismiss();
                break;

        }
    }

    @Override
    public void NoPatientDialog() {
        Dialog_Fail.Builder builder_fail = new Dialog_Fail.Builder(aty);
        builder_fail.setMessage("未查到该病人信息");
        builder_fail.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });

        builder_fail.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
        builder_fail.create().show();
    }

    @Override
    public void bloodDialog(int status) {
        switch (status) {
            case AppConfig.BLOOD_DIALOG_REPEAT:
                display_bloodrepeat();
                break;
            case AppConfig.BLOOD_DIALOG_UNPASS:
                display_bloodunpass();
                break;
            case AppConfig.BLOOD_DIALOG_PASS:
                if(PreferenceHelper.readBoolean(aty, AppConfig.MOBILE_INFO, AppConfig.COLLECTION_ISCHECK)) {
                    display_bloodpass();
                }else {
                    display_bloodover("采血成功");
                }
                break;
        }
    }

    @Override
    public void saveSingleTypes(ArrayList<Sign_Single> sign_singles) {
        ((AppContext) this.getApplication()).setSingleTypes(sign_singles);
    }

    private void display_bloodrepeat() {
        final Dialog_BloodRepeat.Builder dialog_repeat = new Dialog_BloodRepeat.Builder(aty);
        dialog_repeat.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        dialog_repeat.create().show();
    }

    private void display_bloodunpass() {
        final Dialog_BloodUnpass.Builder dialog_unpass = new Dialog_BloodUnpass.Builder(aty);
        dialog_unpass.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        dialog_unpass.create().show();
    }

    private void display_bloodover(String result) {
        final Dialog_BloodPass.Builder dialog_pass = new Dialog_BloodPass.Builder(aty);
        dialog_pass.setMessage(result);
        dialog_pass.create().show();
        handler_blood = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    Log.v("time", msg.what + "");
                } else {
                    countTime = 3;
                    if (time != null) {
                        time.cancel();
                        time = null;
                    }

                    if (timetask != null) {
                        timetask.cancel();
                        timetask = null;
                    }
                    dialog_pass.dismiss();
                }
                super.handleMessage(msg);
            }

        };

        time = new Timer(true);
        timetask = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler_blood.sendMessage(msg);

            }

        };
        time.schedule(timetask, 0, 1000);
    }

    public void display_bloodpass()
    {
        builder_success = new Dialog_Success.Builder(aty);
        builder_success.setMessage("采血成功，是否立即发送");
        builder_success.setPositiveButton("立即发送",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        presenter_bloodcollection.collect("", code, PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                        dialog.dismiss();
                    }
                });

        builder_success.setNegativeButton("稍后发送",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_success.create().show();
    }

    @Override
    public void onResume(){
        super.onResume();
        startBarcodeBroadcastReceiver();
        presenter.getSingleTypes(Visitno);
    }

    @Override
    public void onStop(){
        super.onStop();
        stopBarcodeBroadcastReceiver();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        stopBarcodeBroadcastReceiver();
    }

    /**
     * 停止接收广播
     */
    private void stopBarcodeBroadcastReceiver() {
        try {
            if (valueBroadcastReceiver != null)
                unregisterReceiver(valueBroadcastReceiver);
        } catch (Exception e) {

        }
    }

    /**
     * 开始接收广播
     */
    private void startBarcodeBroadcastReceiver() {
        try {
            if (valueBroadcastReceiver == null)
                valueBroadcastReceiver = new ValueBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("lachesis_barcode_value_notice_broadcast");
            registerReceiver(valueBroadcastReceiver, filter);
        } catch (Exception e) {

        }
    }

    /**
     * 关机广播接收者
     *
     * @author
     *
     */
    private class ValueBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            Log.i("ValueBroadcastReceiver", "onReceive......");
            final String value = arg1
                    .getStringExtra("lachesis_barcode_value_notice_broadcast_data_string");
            if(!value.equals(""))
            {
                if (value.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))) {
                    String type_tag=value.substring(8,9);
                    if(type_tag.equals(AppConfig.TAG_INJECTION)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("source", AppConfig.SEARCH);
                        bundle.putString("id", value);
                        bundle.putString("type", AppConfig.INJECTION);
                        showActivity(aty, Act_DocAdvice.class, bundle);
                    }
                    else if(type_tag.equals(AppConfig.TAG_DISPENSING))
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("source", AppConfig.SEARCH);
                        bundle.putString("id", value);
                        bundle.putString("type", AppConfig.DISPENSING);
                        showActivity(aty, Act_DocAdvice.class, bundle);
                    }
                } else if (value.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_CX_RULE))) {
                    code = value;
                    presenter.collect(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO),code,
                            PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                }else if (value.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_WD_RULE))) {
                    PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO, value);
                    AppConfig.VISITNO = value;
                    Visitno = value;
                    presenter.showPatientDetail(Visitno);
                }  else {
                    Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Override
    public void collectSend(Boolean isSuccess, Collectinfo collectinfo) {
        if(isSuccess)
        {
            display_bloodover("发送成功");
        }
        else {
            display_bloodover("发送失败");
        }
        dialog.dismiss();
    }
}
